package cn.ingrun.cloud_disk.service.Impl;

import cn.ingrun.cloud_disk.mapper.UserMapper;
import cn.ingrun.cloud_disk.model.ResponseJson;
import cn.ingrun.cloud_disk.model.User;
import cn.ingrun.cloud_disk.service.UserService;
import cn.ingrun.cloud_disk.utils.MyResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User get(int id) {
        return userMapper.get(id);
    }

    @Override
    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    public User getUserByPhoneNumber(String phone_number) {
        return userMapper.getUserByPhoneNumber(phone_number);
    }


    // 用户注册
    @Override
    public ResponseJson register(User user) {
        ResponseJson responseJson = user.checkUser();
        if (responseJson.getCode() == 1){
            user.setMD5Password();
            responseJson = user.emailOrPhone_number();
            if (responseJson.getCode() == 1){
                // 用户以邮箱进行注册
                if( userMapper.getUserByEmail(user.getEmail()) != null ){
                    responseJson.setMessage("该邮箱已经注册！");
                    responseJson.setCode(0);
                    return responseJson;
                }
            }
            if (responseJson.getCode() == 2){
                // 用户以手机号进行注册
                if (userMapper.getUserByPhoneNumber(user.getPhone_number()) == null){
                    responseJson.setMessage("该手机号已经注册！");
                    responseJson.setCode(0);
                    return responseJson;
                }
            }

            if (responseJson.getCode() == 3){
                // 用户手机号与邮箱都存在
                if (userMapper.getUserByPhoneNumber(user.getPhone_number()) != null || userMapper.getUserByEmail(user.getEmail()) != null){
                    responseJson.setMessage("该手机号或邮箱已经注册！");
                    responseJson.setCode(0);

                    return responseJson;
                }
            }
            responseJson.setCode(userMapper.register(user.setEmptyForNull()));
            responseJson.setMessage("success");
            user.setPassword("");
            responseJson.setData(user);
            return responseJson;
        }
        return responseJson;
    }


}
